'use strict';
const roles = require('../constants/constant').roles;
const models = require('../models');
const Organization = models.Organization;
const Role = models.Role;
const Team = models.Team;
const teams = require('../config/team');
const UserService = require('../services/user-services');
const TeamUser = models.TeamUser;
const co = require('co');
module.exports = {
  up: function (queryInterface, Sequelize) {
    return co(function*() {
      let allRoles = yield Object.keys(roles).map(roleName => {
        return Role.create({
          roleName: roleName,
          id: roles[roleName]
        });
      });
      console.log('角色创建完毕, 开始查找店铺');
      let orgData = yield  queryInterface.sequelize.query('select distinct storeId, storeName, storeName as name  from users where storeId<>\'\'');

      let orgs = yield orgData[0].map((org) => {
        console.log('遍历店铺', org);
        let roleId = roles.SUPPLIER_ROLE;
        if (org.storeId === 'SUPER007') {
          roleId = roles.PLATFORM_ROLE;
        }
        return Organization.create(Object.assign({}, org, {roleId: roleId}));
      });

      let validOrgs = orgs.filter(org => teams[org.storeId]);
      for (let org of validOrgs) {
        let orgTeams = teams[org.storeId];
        let services = orgTeams['services'];
        let transcoder = orgTeams['transcoder'];
        let mainServices = orgTeams['mainServices'];
        if (services) {
          let team = yield Team.create({
            teamName: org.name + '客服',
            organizationId: org.id,
            roleId: roles.CUSTOMER_SERVICE_ROLE
          });
          for (let uid of services) {
            let user = yield UserService.findOrRegister(uid);
            if (user) {
              yield TeamUser.create({
                teamId: team.id,
                userId: user.id,
                displayName: user.nickname,
                isMaster: user.uid === mainServices[0]
              });
            }
          }
        }

        if (transcoder) {
          let team = yield Team.create({
            teamName: org.name + '译码',
            organizationId: org.id,
            roleId: roles.TRANSCODER_ROLE
          });

          for (let uid of transcoder) {
            let user = yield UserService.findOrRegister(uid);
            yield TeamUser.create({
              teamId: team.id,
              userId: user.id,
              displayName: user.nickname,
              isMaster: user.uid === mainServices[0]
            });
          }
        }
      }
    });
  },

  down: function (queryInterface, Sequelize) {
    /*
     Add reverting commands here.
     Return a promise to correctly handle asynchronicity.

     Example:
     return queryInterface.dropTable('users');
     */
  }
};
